<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>电影类别信息</title>
</head>
<body>
<h1>恭喜你，<span th:text="${username}"></span> 管理员登录成功！</h1>
<a th:href="@{/adminSuccessPage(username=${username}, page=0, size=10)}">用户信息</a>
<a th:href="@{/adminTicketsPage(username=${username}, page=0, size=10)}">购票信息</a>
<a th:href="@{/adminMoviesPage(username=${username}, page=0, size=10)}">电影信息</a>
<a th:href="@{/adminGenersPage(username=${username}, page=0, size=10)}">类别信息</a>
<a th:href="@{/adminDirectorsPage(username=${username}, page=0, size=10)}">导演信息</a>
<a th:href="@{/adminActorsPage(username=${username}, page=0, size=10)}">演员信息</a>
<a th:href="@{/adminReviewsPage(username=${username}, page=0, size=10)}">评论信息</a>

<!-- 添加搜索框和搜索按钮 -->
<form id="searchForm">
    <input type="hidden" th:name="username" th:value="${username}">
    <input type="hidden" th:name="size" th:value="${pageSize}">
    <input type="hidden" th:name="page" th:value="0">
    <label for="searchGname">根据类别名称搜索:</label>
    <input type="text" id="searchGname" name="gname">
    <input type="button" value="搜索" onclick="searchGeners()">
</form>

<h2>电影类别列表</h2>
<button id="addGenersBtn">新增电影类别</button>
<table>
    <thead>
    <tr>
        <th>类型编号</th>
        <th>类型名称</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody id="genersTableBody">
    <tr th:each="geners : ${geners}">
        <td th:text="${geners.gid}"></td>
        <td th:text="${geners.gname}"></td>
        <td>
            <button th:onclick="'editGeners(' + ${geners.gid} + ')'">修改</button>
            <button th:onclick="'deleteGeners(' + ${geners.gid} + ')'">删除</button>
        </td>
    </tr>
    </tbody>
</table>

<!-- 新增电影类别表单 -->
<div id="addGenersForm" style="display: none;">
    <h3>新增电影类别</h3>
    <form id="addGenersFormData">
        <label for="addGname">类型名称:</label>
        <input type="text" id="addGname" name="gname" required><br>
        <button type="button" onclick="submitAddGenersForm()">提交</button>
        <button type="button" onclick="cancelAddGenersForm()">取消</button>
    </form>
</div>

<!-- 修改电影类别表单 -->
<div id="editGenersForm" style="display: none;">
    <h3>修改电影类别信息</h3>
    <form id="editGenersFormData">
        <input type="hidden" id="editGid" name="gid">
        <label for="editGname">类型名称:</label>
        <input type="text" id="editGname" name="gname" required><br>
        <button type="button" onclick="submitEditGenersForm()">提交</button>
        <button type="button" onclick="cancelEditGenersForm()">取消</button>
    </form>
</div>

<!-- 分页导航栏 -->
<div>
    <!-- 首页 -->
    <a th:href="@{/adminGenersPage(username=${username}, page=0, size=${pageSize})}">首页</a>

    <!-- 上一页 -->
    <a th:if="${currentPage > 0}" th:href="@{/adminGenersPage(username=${username}, page=${currentPage - 1}, size=${pageSize})}">上一页</a>

    <!-- 下一页 -->
    <a th:if="${currentPage < totalPages - 1}" th:href="@{/adminGenersPage(username=${username}, page=${currentPage + 1}, size=${pageSize})}">下一页</a>

    <!-- 末页 -->
    <a th:href="@{/adminGenersPage(username=${username}, page=${totalPages - 1}, size=${pageSize})}">末页</a>

    <!-- 显示当前页和总页数 -->
    <span>当前页: <span th:text="${currentPage + 1}"></span> / 总页数: <span th:text="${totalPages}"></span></span>
    <form th:action="@{/adminGenersPage}" method="get">
        <input type="hidden" th:name="username" th:value="${username}">
        <input type="hidden" th:name="size" th:value="${pageSize}">
        <label for="pageNumber">跳转到页数:</label>
        <input type="number" id="pageNumber" name="page" min="0" th:max="${totalPages - 1}" required>
        <input type="submit" value="跳转">
    </form>
</div>

<script>
    document.getElementById('addGenersBtn').addEventListener('click', function () {
        document.getElementById('addGenersForm').style.display = 'block';
    });

    function searchGeners() {
        const gname = document.getElementById('searchGname').value;
        console.log('Search gname:', gname);
        fetch(`/geners/searchGeners?gname=${gname}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                console.log('Response data:', data);
                const tableBody = document.getElementById('genersTableBody');
                tableBody.innerHTML = '';
                if (data.success) {
                    if (data.geners.length === 0) {
                        const row = document.createElement('tr');
                        row.innerHTML = `<td colspan="3">未找到符合条件的电影类别。</td>`;
                        tableBody.appendChild(row);
                    } else {
                        data.geners.forEach(geners => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                            <td>${geners.gid}</td>
                            <td>${geners.gname}</td>
                            <td>
                                <button onclick="editGeners(${geners.gid})">修改</button>
                                <button onclick="deleteGeners(${geners.gid})">删除</button>
                            </td>
                        `;
                            tableBody.appendChild(row);
                        });
                    }
                } else {
                    alert(data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

    function submitAddGenersForm() {
        const formData = new FormData(document.getElementById('addGenersFormData'));
        const geners = {};
        formData.forEach((value, key) => {
            geners[key] = value;
        });

        fetch('/geners/addGeners', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(geners)
        })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.success) {
                    location.reload();
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

    function cancelAddGenersForm() {
        document.getElementById('addGenersForm').style.display = 'none';
        document.getElementById('addGenersFormData').reset();
    }

    function deleteGeners(gid) {
        if (confirm('确定要删除该电影类别吗？')) {
            fetch(`/geners/deleteGeners/${gid}`, {
                method: 'DELETE'
            })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    if (data.success) {
                        location.reload();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }
    }

    function editGeners(gid) {
        // 获取电影类别数据并填充表单
        fetch(`/geners/infoGeners?gid=${gid}`)
            .then(response => response.json())
            .then(geners => {
                if (geners.success) {
                    document.getElementById('editGenersForm').style.display = 'block';
                    document.getElementById('editGid').value = geners.geners.gid;
                    document.getElementById('editGname').value = geners.geners.gname;
                } else {
                    alert(geners.error);
                }
            })
            .catch(error => {
                console.error('Error fetching geners data:', error);
            });
    }

    function cancelEditGenersForm() {
        document.getElementById('editGenersForm').style.display = 'none';
        document.getElementById('editGenersFormData').reset();
    }

    function submitEditGenersForm() {
        const formData = new FormData(document.getElementById('editGenersFormData'));
        const geners = {};
        formData.forEach((value, key) => {
            geners[key] = value;
        });

        fetch('/geners/updateGeners', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(geners)
        })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.success) {
                    location.reload();
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }
</script>
</body>
</html>